<?php
/**
 * Created by PhpStorm.
 * User: dell
 * Date: 2019/5/21
 * Time: 15:14
 */
namespace Modules\Api\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Lib\sms;
use App\Models\InvitRecord;
use App\Models\User;
use App\Models\UserScoreRecord;
use App\Models\Wechart;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Modules\Wechat\Logics\WechatLogic;

class UserController extends Controller{

    //获取openid
    public function getOpenid(Request $request){
        try{
            $jsCode = $request->input("js_code",false);
            if (!$jsCode)return self::error(1000);
            $wx = Wechart::info();
            $openid = WechatLogic::codeToSession($jsCode,$wx->app_id,$wx->app_secret);
            if ($openid){
                return self::success(["openid"=>$openid]);
            }else{
                return self::error(1001);
            }
        }catch (\Exception $e){
            Log::error($e);
            return self::error(500);
        }
    }

    //注册登录
    public function login(Request $request){
        try{
            $nickname = $request->input("nickname",false);
            $avatar = $request->input("avatar",false);
            $openid = $request->input("openid",false);
            $parentId = $request->input("parent_id");
            if (!$openid)return self::error(1000);
            //查询用户是否登录
            $user = User::where("openid",$openid)->first();
            if (!$user) {
                //注册
                $user = new User();
                $user->nickname = json_encode($nickname);
                $user->avatar = $avatar;
                $user->openid = $openid;
                $user->token = str_random(32);
                $user->created_at = Carbon::now();
                $user->save();
                //查询用户
                $parentUser = User::find($parentId);
                if ($parentUser){
                    //开启事务
                    DB::beginTransaction();
                    //判断用户身份,修改邀请人信息
                    if ($parentUser->user_type!=2) {
                        $user->user_type=1;
                        $user->sell_id = $parentUser->sell_id;
                        $user->parent_id = $parentUser->id;
                        $user->save();
                    }else{
                        $user->user_type=3;
                        $user->sell_id = $parentUser->id;
                        $user->save();
                    }
                    //添加邀请记录
                    $invit = new InvitRecord();
                    $invit->user_id = $user->id;
                    $invit->invit_user_id = $parentId;
                    $invit->sell_user_id = $parentUser->parent_id;
                    $invit->invit_status = 1;
                    $invit->created_at = Carbon::now();
                    $invit->save();
                    DB::commit();
                }
                return self::success(['user'=>$user]);
            }else {
                $user->token = str_random(32);
                $user->save();
                return self::success(['user'=>$user]);
            }
        }catch (\Exception $e){
            Log::error($e);
            DB::rollback();
            return self::error(500);
        }
    }

    //获取个人信息
    public function userInfo(Request $request){
        try{
            //接收参数
            $openid = $request->input("openid",false);
            if (!$openid)return self::error(1000);
            $user = User::where("openid",$openid)->first();
            if (!$user)return self::error(1003);
            return self::success($user);
        }catch (\Exception $e){
            Log::error($e);
            return self::error(500);
        }
    }

    //发送验证码
    public function sendSms(Request $request){
        try{
            $openid = $request->input("openid",false);
            $phone = $request->input("phone",false);
            if (!$openid || !$phone)return self::error(1000);
            $user = User::where("openid",$openid)->first();
            if (!$user)return self::error(1002);
            $note = new sms();
            $res = $note->sms($phone);
            if (!$res)return self::error(1017);
            $verify = new \App\Models\Sms();
            $verify->openid = $openid;
            $verify->phone = $phone;
            $verify->code = $res["random"];
            $verify->status = 0;
            $verify->created_at = Carbon::now();
            $verify->save();

            return self::success();
        }catch (\Exception $e){
            Log::error($e);
            return self::error(500);
        }
    }

    //绑定手机号
    public function userBindPhone(Request $request){
        try{
            $openid = $request->input("openid",false);
            $username = $request->input("username",false);
            $phone = $request->input("phone",false);
            $smsCode = $request->input("sms_code",false);
            if (!$openid || !$username || !$phone || !$smsCode)return self::error(1000);
            $user = User::where("openid",$openid)->first();
            if (!$user)return self::error(1002);
            //验证验证码
            $sms = \App\Models\Sms::where("openid",$openid)->where("phone",$phone)->orderBy('id','desc')->first();
            if (!$sms)return self::error(1017);
            if ($sms->status==1)return self::error(1018);
            if ($smsCode!=$sms->code)return self::error(1019);
            DB::beginTransaction();

            $user->username = $username;
            $user->phone = $phone;
            $user->save();

            $sms->status = 1;
            $sms->save();

            DB::commit();
            //查询用户信息
            $userData = User::where("openid",$openid)->first();
            return self::success($userData);
        }catch (\Exception $e){
            Log::error($e);
            DB::rollback();
            return self::error(500);
        }
    }

    //我的客户
    public function myNextUser(Request $request){
        try{
            $openid = $request->input("openid",false);
            $page = $request->input("page",1);
            $size = $request->input("size",20);
            if (!$openid)return self::error(1000);
            $user = User::where("openid",$openid)->first();
            if (!$user)return self::error(1002);
            if ($user->user_type==2){
                $nextCount = User::where("sell_id", $user->id)->count();
                $nextUser = User::where("sell_id", $user->id)->forPage($page, $size)->orderBy('id', 'desc')->select('id', 'openid','avatar', 'nickname', 'recharge', 'created_at')->get();
            }else {
                $nextCount = User::where("parent_id", $user->id)->count();
                $nextUser = User::where("parent_id", $user->id)->forPage($page, $size)->orderBy('id', 'desc')->select('id', 'openid','avatar', 'nickname', 'recharge', 'created_at')->get();
            }
            if ($nextUser->count()<1){
                return self::error(1003);
            }
            $userArray = [];
            foreach ($nextUser as $item){
                $item['created_at'] = date('Y-m-d H:i:s',strtotime($item['created_at']));
                if ($item['recharge']>0){
                    $item['recharge_text'] = "已充值";
                }else{
                    $item['recharge_text'] = "待充值";
                }

                $userArray[] = $item;
            }
            return self::success(["count"=>$nextCount,"list"=>$userArray]);
        }catch (\Exception $e){
            Log::error($e);
            return self::error(500);
        }
    }


}